package com.rui.study.algorithm.P_动态规划_nxn矩阵最短路径;

import java.util.Random;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-01-03 15:13
 **/
public class Solution3动态规划_状态转移表法 {

    private static final int N = 1000;

    public int minDist(int[][] w) {
        Integer[][] dist = new Integer[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                dist[i][j] = minDist(w, dist, i, j);
            }
        }
        return dist[N-1][N-1];
    }

    private int minDist(int[][] w, Integer[][] dist, int i, int j) {

        if (i == 0 && j == 0) {
            return 0;
        }

        if (i == 0) {
            return w[i][j-1] + dist[i][j-1];
        }

        if (j == 0) {
            return  w[i-1][j] +dist[i-1][j];
        }

        // 上
        int up = w[i-1][j] +dist[i-1][j];
        // 左
        int left = w[i][j-1] + dist[i][j-1];

        return up < left ? up : left;
    }

    public static void main(String[] args) {
        int n = N;
//        int[][] w = {
//                {1,3,5,9,3,2,3,8,6,8},
//                {2,1,4,3,8,6,3,6,2,1},
//                {7,2,3,6,2,5,8,7,6,1},
//                {5,1,5,3,5,6,2,6,3,5},
//                {2,2,3,6,7,5,4,6,3,7},
//                {4,5,5,4,3,5,8,3,4,2},
//                {6,8,4,3,2,6,2,5,6,2},
//                {1,2,5,3,5,6,3,5,2,3},
//                {1,2,3,4,1,6,2,3,8,3},
//                {2,3,6,2,1,4,2,3,4,8}};
        int[][] w = new int[n][n];
        Random random = new Random(43);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                w[i][j] = random.nextInt(10);
            }
        }
        Solution3动态规划_状态转移表法 solution3动态规划状态转移表法 = new Solution3动态规划_状态转移表法();
        long start = System.currentTimeMillis();
        int minDist = solution3动态规划状态转移表法.minDist(w);
        long end = System.currentTimeMillis();
        System.out.println("最短距离: " + minDist + ", 用时:[" + (end - start) + "ms]");
    }
}
